﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;

namespace Z2.Core
{
	internal class MoveableBehavior : ObjectBehaviorBase
	{
		private int m_move;
		private int m_max;
		private int m_direction = 1;


		public MoveableBehavior()
		{
			Speed = 1;
		}

		public int Speed
		{
			get;
			set;
		}
		public int Move 
		{
			get { return this.m_move; }
			set
			{
				this.m_move = value;
				this.m_max = value * WorldField.SIZE;
			}
		}

		private bool CantCollide(ObjectBase thisObj, ObjectBase obj)
		{
			return obj == thisObj || obj is ParticleBasic || thisObj.CantCollide(obj);
		}

		internal override void PerfomActionsOn(ObjectBase objOn, ObjectBase obj, IntersectionResult intersection)
		{
			if (intersection.VerticalType == IntersectionVerticalType.FromTop)
			{
				Rectangle rect = objOn.GetRectangle(0, 0);
				if (intersection.With.Move.X != 0 && (objOn.Position.Y + rect.Height) <= obj.Position.Y)
					objOn.Link = new Vector2(objOn.Change.X + obj.Move.X, objOn.Move.Y);
			}
		}

		internal override void NormalizeVector(ObjectBase obj)
		{
		}

		internal override void ModifyVector(ObjectBase obj)
		{
			Vector2 pos = obj.Position;
			IntersectionResult ir;

			bool cwo = false;
			if (pos.X > (obj.InitialPosition.X + this.m_max) || pos.X < obj.InitialPosition.X)
			{
				this.m_direction *= -1;
				obj.Move = new Vector2(this.Speed * this.m_direction, obj.Move.Y);
				obj.Position = new Vector2(obj.Position.X + obj.Move.X, obj.Position.Y);
			}
			else
			{
				Rectangle rect;
				List<ObjectBase> objects = World.Current.GetSectorsObjects(obj, CantCollide);

				rect = obj.GetRectangle(this.Speed * this.m_direction, 0);

				foreach (ObjectBase objBase in objects)
				{
					if (CantCollide(obj, objBase)) continue;

					ir = obj.Intersects(objBase, rect);
					if (ir.IsCollision)
					{
						cwo = true;
					}
				}

				if (!cwo)
				{
					obj.Move = new Vector2(this.Speed * this.m_direction, obj.Move.Y);
					obj.Position = new Vector2(obj.Position.X + obj.Move.X, obj.Position.Y);
				}
				else
				{
					obj.Move = new Vector2(0, obj.Move.Y);
				}
				
			}
			
		}
	}
}
